package com.roc.learn.goodgoodstudy.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Create {
    public static void main(String[] args) {
        // ①
        Thread t1 = new MyThread();
        t1.start();

        // ②
        Runnable r = new MyRunnable();
        Thread t2 = new Thread(r);
        t2.start();
        // ②的匿名内部类写法
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
            }
        }).start();

        // ③
        Callable<String> call = new MyCallable(100);
        // 把任务对象Callable交给FutureTask
        FutureTask<String> f1 = new FutureTask<>(call);
        Thread t3 = new Thread(f1);
        t3.start();
        try {
            // 如果任务f1没有执行结束，会等待
            String rs1 = f1.get();
            System.out.println("线程t3的结果：" + rs1);
        } catch (Exception e) {
        }
    }
}

// ①继承Thread类，重写run方法
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}

// ②实现Runnable接口，重写run方法i
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(i);
        }
    }
}

// ③实现Callable接口，重写call方法
class MyCallable implements Callable<String> {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return "子线程结果为：" + sum;
    }
}